package chat;

import java.awt.event.*;
import java.io.*;
import java.net.*;
import javax.swing.*;
import java.util.Calendar;

public class Client implements KeyListener {

    int port;
    String ip;
    Socket socket;
    ObjectInputStream input;
    ObjectOutputStream output;
    String inMessage;
    ChatWindow window;
    String nickName;
    Calendar cal;

    Client() {
        try {
            startClient();
            startWindow();
        } catch (IOException e) {
            System.err.println("Couldn't start client: " + e.getMessage());
        }

        try {
            while (true) {
                getMessage();
            }
        } catch (IOException e) {
            System.err.println(e.getMessage());
        } finally {
            close();
        }
    }

    void close() {
        try {
            if (socket != null) {
                socket.close();
            }
            if (input != null) {
                input.close();
            }
            if (output != null) {
                output.close();
            }
        } catch (IOException e) {
            System.err.println("Error in closing");
        }
    }

    void startWindow() throws IOException {
        nickName = JOptionPane.showInputDialog("Choose a nickname: ", null);
        window = new ChatWindow("(Client) "+nickName);
        JFrame chatFrame = new JFrame(window.windowLabel);
        chatFrame.getContentPane().add(window);
        chatFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        chatFrame.pack();
        chatFrame.setVisible(true);
        window.writearea.addKeyListener(this);
        closeListener listener = new closeListener();
        window.closeButton.addActionListener(listener);
        saveTextListener tlistener = new saveTextListener();
        window.saveButton.addActionListener(tlistener);
    }

    void startClient() throws IOException {
        ip = JOptionPane.showInputDialog("To what IP?", null);
        String portString = JOptionPane.showInputDialog("And which port?", null);
        port = Integer.parseInt(portString);
        socket = new Socket(ip, port);
        output = new ObjectOutputStream(socket.getOutputStream());
        input = new ObjectInputStream(socket.getInputStream());
    }

    void getMessage() throws IOException {
        try {
            inMessage = (String) input.readObject();
            if (!inMessage.equals("")) {
                window.readarea.append(inMessage);
            }
        } catch (ClassNotFoundException e) {
            System.out.println("Unexpected object class: " + e.getMessage());
        }
    }

    void sendMessage() throws IOException {
        cal = Calendar.getInstance();
        String time = (cal.get(cal.HOUR_OF_DAY) + ":" + cal.get(cal.MINUTE));
        if (!window.writearea.getText().equals("")) {
            output.writeObject("(" + time + ") " + nickName + ": " + window.writearea.getText());
            output.flush();
            window.writearea.setText("");
        }
    }

    public void keyTyped(KeyEvent event) {
        if (event.getKeyChar() == event.VK_ENTER) {
            try {
                sendMessage();
            } catch (IOException e) {
                System.err.println(e.getMessage());
            }
        }
    }
    public void keyPressed(KeyEvent event) {}
    public void keyReleased(KeyEvent event) {}

    class closeListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            try {
                output.writeObject(nickName+" has disconnected"+"\n");
                output.flush();
            } catch (IOException f) {
                System.err.println(f.getMessage());
            }
            close();
            System.exit(0);
        }
    }

    class saveTextListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            JFileChooser chooser = new JFileChooser();
            int answer = chooser.showSaveDialog(null);

            if (answer == chooser.APPROVE_OPTION) {
                File savefile = chooser.getSelectedFile();
                saveDialog(savefile);
            }

        }

        void saveDialog(File file) {
            try {
                FileWriter fstream = new FileWriter(file);
                BufferedWriter out = new BufferedWriter(fstream);
                out.write(window.readarea.getText());
                out.close();
            } catch (Exception f) {
                System.err.println("Error: " + f.getMessage());
            }
        }
    }
}